/**
 * 
 */
package net.oauth.transport.http.header;

import java.util.LinkedHashMap;
import java.util.Map;

import net.oauth.util.ParameterParser;

/**
 * @author Buhake Sindi
 * @since 09 March 2012
 *
 */
public class HttpHeaderParameterParser implements ParameterParser<String> {
	
	private static final char[] PARAMETER_DELIMITERS = { ';', ',' };

	/* (non-Javadoc)
	 * @see net.oauth.util.ParameterParser#parse(java.lang.String)
	 */
	@Override
	public Map<String, String> parse(String paramString) {
		// TODO Auto-generated method stub
		if (paramString == null || paramString.isEmpty()) {
			return null;
		}
		
		Map<String, String> parameterMap = new LinkedHashMap<String, String>();
		int beginIndex = 0;
		int pos = 0;
		boolean quoted = false;
		while (pos < paramString.length()) {
			char ch = paramString.charAt(pos);
			if (ch == '"') {
				quoted = !quoted;
				continue;
			}
			
			if (isOneOf(ch, PARAMETER_DELIMITERS)) {
				if (!quoted) {
					parseParameter(paramString.substring(beginIndex, pos), parameterMap);
					beginIndex = pos + 1;
				}
			}
			
			pos++;
		}
		
		return parameterMap;
	}
	
	private void parseParameter(String parameter, Map<String, String> paramMap) {
		int pairDelimPos = parameter.indexOf('=');
		if (pairDelimPos == -1) {
			throw new IllegalArgumentException("Invalid parameter: " + parameter);
		}
		
		String name = parameter.substring(0, pairDelimPos);
		String value = parameter.substring(pairDelimPos + 1);
		if (value.charAt(0) == '\"' && value.charAt(value.length() - 1) == '\"') {
			value = value.substring(1, value.length() - 1);
		}
		
		paramMap.put(name, value);
	}
	
	private final boolean isOneOf(final char c, final char[] chars) {
		if (chars == null) {
			throw new IllegalArgumentException("Character sets cannot be null.");
		}
		
		for (char chr : chars) {
			if (chr == c) {
				return true;
			}
		}
		
		return false;
	}
}
